package UILayer;

import ModelLayer.CurrentAccount;
import CtrLayer.StaffCtr;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.*;

public class AccountManager extends JInternalFrame
{
	private JPanel contentPane;
	private JTextField name_tf;
	private JTextField id_tf;
	private JTextField phone_tf;
	private JTextField city_tf;
	private JTextField add_tf;
	private JTextField post_tf;
	private String id;
	private JPanel panel;
	private StaffCtr staff_ctr;
	private JLabel[] empty_error_lbls;
	private JLabel inc_phone_lbl;
	private JLabel inc_post_lbl;
	private JTextField sal_tf;
	private JTextField user_tf;
	private JPasswordField pass_pf;
	private JPasswordField rep_pass_pf;
	private JComboBox comboBox;
	private JLabel wrong_pass_lbl;
	private JLabel inc_sal_lbl;
	private JLabel rep_pass_lbl;
	private JTextField pass_tf;
	private boolean my_account;
	private JLabel us_na_lbl;
	private JLabel pass_lbl;



	public AccountManager(String i_id)
	{
		super("Add account", true, true, true, true);
		id = i_id;
		if (id != null)
		{
			this.setTitle("Edit account");
		}
		my_account = CurrentAccount.get_id().equals(id);
		staff_ctr = new StaffCtr();

		setBounds(100, 100, 428, 472);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));

		panel = new JPanel();
		contentPane.add(panel, BorderLayout.CENTER);
		panel.setLayout(null);

		JPanel panel_1 = new JPanel();
		contentPane.add(panel_1, BorderLayout.SOUTH);
		panel_1.setLayout(new BorderLayout(0, 0));

		JButton ok_btn = new JButton("Ok");

		ok_btn.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				try_to_create_or_edit_account();
			}
		});

		panel_1.add(ok_btn, BorderLayout.WEST);

		JButton cancel_btn = new JButton("Cancel");
		cancel_btn.setHorizontalAlignment(SwingConstants.RIGHT);
		cancel_btn.setForeground(Color.BLACK);
		cancel_btn.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				dispose();
			}
		});
		cancel_btn.setBackground(new Color(240, 240, 240));
		panel_1.add(cancel_btn, BorderLayout.EAST);

		make_logical_error_lbls();
		make_lbls();
		make_tfs();
		make_empty_error_lbls();
	}

	

	private void make_lbls()
	{
		JLabel lblNewLabel = new JLabel("Account data");
		lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 14));
		lblNewLabel.setBounds(10, 11, 138, 14);
		panel.add(lblNewLabel);

		JLabel id_lbl = new JLabel("ID");
		id_lbl.setBounds(10, 45, 67, 14);
		panel.add(id_lbl);

		JLabel name_lbl = new JLabel("Name");
		name_lbl.setBounds(10, 73, 46, 14);
		panel.add(name_lbl);

		JLabel phone_lbl = new JLabel("Phone Number");
		phone_lbl.setBounds(10, 101, 79, 14);
		panel.add(phone_lbl);

		JLabel addr_lbl = new JLabel("Address");
		addr_lbl.setBounds(10, 129, 86, 14);
		panel.add(addr_lbl);

		JLabel cit_lbl = new JLabel("City");
		cit_lbl.setBounds(10, 191, 46, 14);
		panel.add(cit_lbl);

		JLabel pos_co_lbl = new JLabel("Postal code");
		pos_co_lbl.setBounds(10, 160, 86, 14);
		panel.add(pos_co_lbl);
		
		JLabel sal_lbl = new JLabel("Salary");
		sal_lbl.setBounds(10, 222, 46, 14);
		panel.add(sal_lbl);
		
		JLabel fun_lbl = new JLabel("Function");
		fun_lbl.setBounds(10, 253, 46, 14);
		panel.add(fun_lbl);
		
		us_na_lbl = new JLabel("Username");
		us_na_lbl.setBounds(10, 284, 67, 14);
		panel.add(us_na_lbl);
		
		pass_lbl = new JLabel("Password");
		pass_lbl.setBounds(10, 315, 46, 14);
		panel.add(pass_lbl);
		
		rep_pass_lbl = new JLabel("Repeat Password");
		rep_pass_lbl.setBounds(10, 346, 94, 14);
		panel.add(rep_pass_lbl);
		
		comboBox = new JComboBox();
		comboBox.setBounds(113, 250, 86, 20);
		
		if(CurrentAccount.give_rank().equals("owner"))
		{
			if(my_account)
			{
				comboBox.setModel(new DefaultComboBoxModel(new String[] { "Employee", "Manager", "Owner" }));
				
			}
			else
			{
				comboBox.setModel(new DefaultComboBoxModel(new String[] { "Employee", "Manager" }));
			}
		}
		else
		{
			comboBox.setModel(new DefaultComboBoxModel(new String[] { "Employee" }));
		}
		if(my_account)
		{
			comboBox.setEnabled(false);
			rep_pass_lbl.setVisible(false);
		}
		panel.add(comboBox);
		
	}

	private void make_tfs()
	{
		name_tf = new JTextField();
		name_tf.setBounds(113, 70, 86, 20);
		panel.add(name_tf);
		name_tf.setColumns(10);

		id_tf = new JTextField();
		id_tf.setText(staff_ctr.get_next_account_id());
		id_tf.setEnabled(false);
		id_tf.setEditable(false);
		id_tf.setBounds(113, 42, 86, 20);
		panel.add(id_tf);
		id_tf.setColumns(10);

		phone_tf = new JTextField();
		phone_tf.setBounds(113, 98, 86, 20);
		panel.add(phone_tf);
		phone_tf.setColumns(10);

		city_tf = new JTextField();
		city_tf.setBounds(113, 188, 86, 20);
		panel.add(city_tf);
		city_tf.setColumns(10);

		add_tf = new JTextField();
		add_tf.setBounds(113, 126, 86, 20);
		panel.add(add_tf);
		add_tf.setColumns(10);

		post_tf = new JTextField();
		post_tf.setBounds(113, 157, 86, 20);
		panel.add(post_tf);
		post_tf.setColumns(10);
		
		sal_tf = new JTextField();
		sal_tf.setBounds(113, 219, 86, 20);
		panel.add(sal_tf);
		sal_tf.setColumns(10);
			
		user_tf = new JTextField();
		user_tf.setBounds(113, 281, 86, 20);
		panel.add(user_tf);
		user_tf.setColumns(10);
		if(id == null)
		{
			pass_pf = new JPasswordField();
			pass_pf.setBounds(113, 312, 86, 20);
			panel.add(pass_pf);
			
			rep_pass_pf = new JPasswordField();
			rep_pass_pf.setBounds(113, 343, 86, 20);
			panel.add(rep_pass_pf);
		}
		else
		{
			user_tf.setEnabled(false);
			pass_tf = new JTextField();
			pass_tf.setBounds(113, 312, 86, 20);
			pass_tf.setEnabled(false);
			panel.add(pass_tf);
			if(my_account)
			{
				us_na_lbl.setVisible(false);
				user_tf.setVisible(false);
			}
		}
		
		if(id != null)
		{
			fill_tfs();
			make_edit_btns();
		}
	}
		
		
		
	private void make_edit_btns()
	{
		JButton btnChangeUsername = new JButton("Change username");
		btnChangeUsername.setBounds(45, 359, 119, 23);
		btnChangeUsername.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { change_login(); } });
		panel.add(btnChangeUsername);
		
		JButton btnChangePassword = new JButton("Change Password");
		btnChangePassword.setBounds(223, 359, 138, 23);
		btnChangePassword.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { change_password(); } });
		panel.add(btnChangePassword);
	}


	private void fill_tfs()
	{
		String[] data = staff_ctr.give_string_array(id);
		id_tf.setText(data[0]);
		name_tf.setText(data[1]);
		phone_tf.setText(data[2]);
		add_tf.setText(data[3]);
		post_tf.setText(data[4]);
		city_tf.setText(data[5]);
		if(Boolean.parseBoolean(data[9]))
		{
			if(my_account && CurrentAccount.give_rank().equals("owner"))
			{
				comboBox.setSelectedItem("Owner");
			}
			else
			{
				comboBox.setSelectedItem("Manager");
			}
		}
		else
		{
			comboBox.setSelectedItem("Employee");
		}
		sal_tf.setText(data[8]);
		if(my_account)
		{
			sal_tf.setEnabled(false);
			pass_tf.setVisible(false);
			pass_lbl.setVisible(false);
		}
		user_tf.setText(data[6]);
		pass_tf.setText(data[7]);
	}

	private void try_to_create_or_edit_account()
	{
		if (check_for_correctness())
		{
			String name = name_tf.getText();
			String phone_nr = phone_tf.getText();
			boolean is_manager = ((String) comboBox.getSelectedItem()).equals("Manager");
			String city = city_tf.getText();
			String address = add_tf.getText();
			String postal_code = post_tf.getText();
			

			int salary = Integer.parseInt(sal_tf.getText());

			if (id == null)
			{
				String login = user_tf.getText();
				String password = String.valueOf(pass_pf.getPassword());
				if(!(staff_ctr.is_login_used(login)))
				{

					staff_ctr.add_account(name, phone_nr, address, postal_code,
							city, login, password, salary, is_manager);
					JOptionPane.showMessageDialog(this,
							"Successully created an account.", "Success",
							JOptionPane.INFORMATION_MESSAGE);
					dispose();
				}
				else
				{
					JOptionPane.showMessageDialog(this,
							"This username is already used.",
							"Error", JOptionPane.INFORMATION_MESSAGE);
				}
			}
			else
			{
				staff_ctr.edit_name(id, name);
				staff_ctr.edit_address(id, address, postal_code, city);
				
				staff_ctr.edit_phone_nr(id, phone_nr);
				if(!my_account)
				{
					staff_ctr.edit_salary(id, salary);
					staff_ctr.edit_is_manager(id, is_manager);
				}

				JOptionPane.showMessageDialog(this,
						"Successully edited account's information.",
						"Success", JOptionPane.INFORMATION_MESSAGE);
				dispose();
			}

		}
	}
	
	private void make_logical_error_lbls()
	{
		inc_phone_lbl = new JLabel(
				"<html>The phone number is incorrect.<br/>Please enter valid danish phone number.</html>");
		inc_phone_lbl.setForeground(Color.RED);
		inc_phone_lbl.setLabelFor(city_tf);
		inc_phone_lbl.setBounds(202, 86, 230, 42);
		inc_phone_lbl.setVisible(false);
		panel.add(inc_phone_lbl);

		inc_post_lbl = new JLabel("Enter valid Danish postal code.");
		inc_post_lbl.setForeground(Color.RED);
		inc_post_lbl.setBounds(202, 160, 290, 14);
		inc_post_lbl.setVisible(false);
		panel.add(inc_post_lbl);
		
		wrong_pass_lbl = new JLabel("<html><p>Password and it's repetition don't match<p><html>");
		wrong_pass_lbl.setForeground(Color.RED);
		wrong_pass_lbl.setBounds(202, 325, 138, 28);
		wrong_pass_lbl.setVisible(false);
		panel.add(wrong_pass_lbl);
		
		inc_sal_lbl = new JLabel("<html><p>You must provide a correct positive number.<p><html>");
		inc_sal_lbl.setForeground(Color.RED);
		inc_sal_lbl.setBounds(202, 219, 162, 28);
		inc_sal_lbl.setVisible(false);
		panel.add(inc_sal_lbl);
	}

	private boolean check_for_correctness()
	{
		inc_phone_lbl.setVisible(false);
		inc_post_lbl.setVisible(false);
		wrong_pass_lbl.setVisible(false);
		inc_sal_lbl.setVisible(false);
		for(int i = 0; i < 5; i++)
		{
			empty_error_lbls[i].setVisible(false);
		}

		boolean[] display_lbl = { true, true, true, true };
		String phone = phone_tf.getText();
		String new_phone;
		if (phone.matches("\\+?[0-9]+(:?-[0-9]+)*"))
		{
			if (phone.contains("-"))
			{
				new_phone = phone.replaceAll("-", "");
			}
			else
			{
				new_phone = phone;
			}

			if ((new_phone.length() == 8)
					|| (new_phone.length() == 11 && new_phone.startsWith("+")))
			{
				display_lbl[0] = false;
			}
		}
		
		if (post_tf.getText().matches("[0-9]+")
				&& post_tf.getText().length() == 4)
		{
			display_lbl[1] = false;
		}
		else
		{
			display_lbl[1] = true;
		}
		
		String sal = sal_tf.getText();
		if(!my_account)
		{
			if(int_convertable(sal))
			{
				int salary = Integer.parseInt(sal);
				{
					if(salary > 0)
					{
						display_lbl[2] = false;
					}
				}
			}
		}
		else
		{
			display_lbl[2] = false;
		}
		
		if(id == null)
		{
			if(String.valueOf(pass_pf.getPassword()).equals(String.valueOf(rep_pass_pf.getPassword())))
			{
				display_lbl[3] = false;
			}
		}
		else
		{
			display_lbl[3] = false;
		}

		return display_error_lbls(display_lbl);
	}

	private boolean display_error_lbls(boolean[] display_lbl)
	{
		boolean returner = true;
		if (name_tf.getText().equals(""))
		{
			empty_error_lbls[0].setVisible(true);
			returner = false;
		}
		if (add_tf.getText().equals(""))
		{
			empty_error_lbls[1].setVisible(true);
			returner = false;
		}
		if (city_tf.getText().equals(""))
		{
			empty_error_lbls[2].setVisible(true);
			returner = false;
		}
		if (phone_tf.getText().equals(""))
		{
			inc_phone_lbl.setVisible(true);
			returner = false;
		}
		if (post_tf.getText().equals(""))
		{
			inc_post_lbl.setVisible(true);
			returner = false;
		}
		
		if(user_tf.getText().equals(""))
		{
			empty_error_lbls[3].setVisible(true);
			returner = false;
		}
		if(id == null)
		{
			if(String.valueOf(pass_pf.getPassword()).equals(""))
			{
				empty_error_lbls[4].setVisible(true);
				returner = false;
			}
		}
		
		
		else if(display_lbl[3])
		{
			wrong_pass_lbl.setVisible(true);
			returner = false;
		}
		
		if (display_lbl[0])
		{
			inc_phone_lbl.setVisible(true);
			returner = false;
		}
		if (display_lbl[1])
		{
			inc_post_lbl.setVisible(true);
			returner = false;
		}
		if(display_lbl[2])
		{
			inc_sal_lbl.setVisible(true);
			returner = false;
		}
		

		return returner;
	}

	private void make_empty_error_lbls()
	{
		int[][] coords = { { 202, 73 }, { 202, 129 }, { 202, 191 }, { 202, 284 }, { 202, 315 } };
		empty_error_lbls = new JLabel[5];
		for (int i = 0; i < 5; i++)
		{
			empty_error_lbls[i] = new JLabel("Fill.");
			empty_error_lbls[i].setForeground(Color.RED);
			empty_error_lbls[i].setBounds(coords[i][0], coords[i][1], 150, 14);
			empty_error_lbls[i].setVisible(false);
			panel.add(empty_error_lbls[i]);
		}
	}
	
	private boolean int_convertable(String data)
	{
		try
		{
			int i = Integer.parseInt(data);
			if (i < 0)
			{
				return false;
			}
		}
		catch (NumberFormatException nfe)
		{
			return false;
		}
		return true;
	}
	
	private void refresh()
	{
		fill_tfs();
	}
	
	private void change_login()
	{
		LoginChanger l = new LoginChanger(user_tf.getText());
		JDesktopPane desktop = getDesktopPane();
		desktop.add(l);
		Point current_win = getLocationOnScreen();
		int x = (int) current_win.getX() + 20;
		int y = (int) current_win.getY() + 5;
		l.setLocation(x, y);
		l.setVisible(true);
	}
	
	private void change_password()
	{
		PasswordChanger p = new PasswordChanger();
		JDesktopPane desktop = getDesktopPane();
		desktop.add(p);
		Point current_win = getLocationOnScreen();
		int x = (int) current_win.getX() + 20;
		int y = (int) current_win.getY() + 5;
		p.setLocation(x, y);
		p.setVisible(true);
		
	}
	
	
	class PasswordChanger extends JInternalFrame
	{
		private JPasswordField rep_pass_pf;
		private JPasswordField pass_pf;
		private JLabel wrong_pass_lbl;


		public PasswordChanger()
		{
			super("Change password", false, false, false, true);
			setBounds(100, 100, 357, 294);
			getContentPane().setLayout(null);
			
			JLabel ins_new_pass_lbl = new JLabel("Insert new password");
			ins_new_pass_lbl.setFont(new Font("Times New Roman", Font.BOLD, 14));
			ins_new_pass_lbl.setBounds(10, 11, 145, 14);
			getContentPane().add(ins_new_pass_lbl);
			
			JLabel lblPassword = new JLabel("Password");
			lblPassword.setBounds(10, 60, 46, 14);
			getContentPane().add(lblPassword);
			
			JLabel lblRepeatPassword = new JLabel("Repeat Password");
			lblRepeatPassword.setBounds(10, 96, 96, 14);
			getContentPane().add(lblRepeatPassword);
			
			rep_pass_pf = new JPasswordField();
			rep_pass_pf.setBounds(116, 93, 106, 20);
			getContentPane().add(rep_pass_pf);
			
			pass_pf = new JPasswordField();
			pass_pf.setBounds(116, 57, 106, 20);
			getContentPane().add(pass_pf);
			
			JButton ok_btn = new JButton("Ok");
			ok_btn.setBounds(10, 236, 89, 23);
			ok_btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { change(); } });
			getContentPane().add(ok_btn);
			
			JButton cancel_btn = new JButton("Cancel");
			cancel_btn.setBounds(202, 236, 89, 23);
			cancel_btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } });
			getContentPane().add(cancel_btn);
			
			wrong_pass_lbl = new JLabel("<html><p>Password and its repetition don't match<p><html>");
			wrong_pass_lbl.setForeground(Color.RED);
			wrong_pass_lbl.setBounds(232, 60, 99, 50);
			wrong_pass_lbl.setVisible(false);
			getContentPane().add(wrong_pass_lbl);

		}
		
		private void change()
		{
			wrong_pass_lbl.setVisible(false);
			String password = String.valueOf(pass_pf.getPassword());
			if (password.equals(String.valueOf(rep_pass_pf.getPassword())))
			{
				JPasswordField my_pass_pf = new JPasswordField();
				int result = JOptionPane.showConfirmDialog(null, my_pass_pf, "Insert your password.", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
				if(result == JOptionPane.OK_OPTION)
				{
					String my_password = String.valueOf(my_pass_pf.getPassword());
					if(CurrentAccount.check_password(my_password))
					{
						staff_ctr.edit_password(id, password);
						refresh();
						JOptionPane.showMessageDialog(this,
								"Password successfully changed.", "Success",
								JOptionPane.INFORMATION_MESSAGE);
						dispose();
					}
					else
					{
						JOptionPane.showMessageDialog(this,
								"Your password is incorrect.", "Error",
								JOptionPane.INFORMATION_MESSAGE);
					}
				}
			}
			else
			{
				wrong_pass_lbl.setVisible(true);
			}
			
		}
	}
	
	class LoginChanger extends JInternalFrame
	{
		private JTextField login_tf;
		private String old_login;


		public LoginChanger(String i_old_login)
		{
			super("Change username", false, false, false, true);
			setBounds(100, 100, 251, 143);
			getContentPane().setLayout(null);
			
			JLabel ins_new_login_lbl = new JLabel("Insert new username");
			ins_new_login_lbl.setFont(new Font("Times New Roman", Font.BOLD, 14));
			ins_new_login_lbl.setBounds(10, 11, 145, 14);
			getContentPane().add(ins_new_login_lbl);
			
			JButton ok_btn = new JButton("Ok");
			ok_btn.setBounds(10, 79, 89, 23);
			ok_btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { change(); } });
			getContentPane().add(ok_btn);
			
			JButton cancel_btn = new JButton("Cancel");
			cancel_btn.setBounds(120, 79, 89, 23);
			cancel_btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } });
			getContentPane().add(cancel_btn);
			
			JLabel lblLogin = new JLabel("Username");
			lblLogin.setBounds(10, 36, 60, 14);
			getContentPane().add(lblLogin);
			
			login_tf = new JTextField();
			login_tf.setBounds(75, 36, 86, 20);
			getContentPane().add(login_tf);
			login_tf.setColumns(10);

		}
		
		private void change()
		{
			
			String login = login_tf.getText();
			if (!(staff_ctr.is_login_used(login)) || login.equals(old_login))
			{
				JPasswordField my_pass_pf = new JPasswordField();
				int result = JOptionPane.showConfirmDialog(null, my_pass_pf, "Insert your password.", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
				if(result == JOptionPane.OK_OPTION)
				{
					String my_password = String.valueOf(my_pass_pf.getPassword());
					if(CurrentAccount.check_password(my_password))
					{
						
						staff_ctr.edit_login(id, login);
						old_login = login;
						refresh();
						JOptionPane.showMessageDialog(this,
								"Username successfully changed.", "Success",
								JOptionPane.INFORMATION_MESSAGE);
						dispose();
					}
					else
					{
						JOptionPane.showMessageDialog(this,
								"Your password is incorrect.", "Error",
								JOptionPane.INFORMATION_MESSAGE);
					}
				}
			}
			else
			{
				JOptionPane.showMessageDialog(this,
						"This login is already taken.", "Error",
						JOptionPane.INFORMATION_MESSAGE);
			}
			
		}
	}

}
